package com.xm.httpapi.BaseUtils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @desc 线程池管理
 * @auth guohaijin
 * @time 2020/11/14
 */
public class ThreadPool {
    private static ExecutorService pool = null;
    private volatile static ThreadPool sInstance;
    /**
     * @desc 单线程池
     */
    private static final int SINGLE_THREAD = 1;

    /**
     * @desc 可缓存线程池
     */
    private static final int CACHED_THREAD = 2;

    /**
     * @desc 固定线程池
     */
    private static final int FIXED_THREAD = 3;

    public static ThreadPool getIntance() {
        return init(SINGLE_THREAD, -1);
    }

    public static ThreadPool getCachedIntance() {
        return init(CACHED_THREAD, -1);
    }

    public static ThreadPool getFixedIntance(int num) {
        return init(FIXED_THREAD, num);
    }

    public static ThreadPool init(int model, int num) {
        if (sInstance == null) {
            synchronized (ThreadPool.class) {
                if (sInstance == null) {
                    sInstance = new ThreadPool(model, num);
                }
            }
        }
        return sInstance;
    }

    private ThreadPool(int model, int num) {
        if (pool != null) return;
        try {
            switch (model) {
                case SINGLE_THREAD:
                    pool = Executors.newSingleThreadExecutor();
                    break;
                case CACHED_THREAD:
                    pool = Executors.newCachedThreadPool();
                    break;
                case FIXED_THREAD:
                    pool = Executors.newFixedThreadPool(num);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void execute(Runnable r) {
        if (pool == null || pool.isShutdown()) {
            // 线程池获取失败，则直接使用线程
            new Thread(r).start();
            return;
        }
        pool.execute(r);
    }

    public void shutDown() {
        if (pool == null || pool.isShutdown()) return;
        pool.shutdownNow();
        pool = null;
    }
}
